package com.cloudkinto.service.orderqoo.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.bo.order.OrderQooQueryBo;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.error.ErrorEnum;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.exception.NotSufficientFundsException;
import com.cloudkinto.common.utils.ExcelUtils;
import com.cloudkinto.common.utils.OrderCodeUtil;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.finance.CompanyAccountService;
import com.cloudkinto.service.operate.OperateRecordService;
import com.cloudkinto.service.operate.vo.OperateRes;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.orderoutput.vo.OrderOutputAddReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputPackageAddReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputProductAddReq;
import com.cloudkinto.service.orderqoo.OrderQoo10Service;
import com.cloudkinto.service.orderqoo.vo.*;
import com.cloudkinto.service.product.ProductCombinationService;
import com.cloudkinto.service.product.ProductInfoService;
import com.cloudkinto.service.region.JpRegionService;
import com.cloudkinto.service.shipprice.ShipPriceService;
import com.cloudkinto.service.shop.ShopService;
import com.cloudkinto.service.stock.StockRecordService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author zhangyy
 * @since 2020-08-13
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
@RequiredArgsConstructor
public class OrderQoo10ServiceImpl extends ServiceImpl<OrderQoo10Dao, OrderQoo10Do> implements OrderQoo10Service {
    private final RestTemplate restTemplate;
    private final OrderOutputDao orderOutputDao;
    private final OrderOutputPackageDao orderOutputPackageDao;
    //    private final OrderOutputProductDao orderOutputProductDao;
//    private final DicBusinessItemDao dicBusinessItemDao;
    private final ShopDao shopDao;
    private final CompanyDao companyDao;
    //    private final OrderOutputService orderOutputService;
    private final OperateRecordService operateRecordDao;
    private final ShopService shopService;
    //    private final UserDao userDao;
    private final CompanyAccountService companyAccountService;
    private final OrderOutputService outputService;
    private final ProductInfoDao productInfoDao;
    private final StorageDao storageDao;
    private final JpRegionService mRegionService;
    private final StockRecordDao stockRecordDao;
    //    private final ShipPriceService shipPriceService;
//    private final ProductSkuMapDao productSkuMapDao;
    private final ProductInfoService productInfoService;
    private final ProductCombinationService productCombinationService;
    private final StockRecordService stockRecordService;

    @Override
    public SingleResult addInit(Long userId, Long companyId) {
        Map result = new HashMap();

        List<Map> ShippingStatList = new ArrayList<>();
        Map map = new HashMap();
        map.put("id", 1);
        map.put("value", "等待支付");
        ShippingStatList.add(map);
        map = new HashMap();
        map.put("id", 2);
        map.put("value", "支付完成");
        ShippingStatList.add(map);
        map = new HashMap();
        map.put("id", 3);
        map.put("value", "发货确认");
        ShippingStatList.add(map);
        map = new HashMap();
        map.put("id", 4);
        map.put("value", "配送中");
        ShippingStatList.add(map);
        map = new HashMap();
        map.put("id", 5);
        map.put("value", "配送完了");
        ShippingStatList.add(map);
        map = new HashMap();
        map.put("id", 6);
        map.put("value", "取消/退换");
        ShippingStatList.add(map);

        result.put("ShippingStatList", ShippingStatList);


        List<Map> searchConditionList = new ArrayList<>();
        map = new HashMap();
        map.put("id", 1);
        map.put("value", "注文日");
        searchConditionList.add(map);
        map = new HashMap();
        map.put("id", 2);
        map.put("value", "決済完了日");
        searchConditionList.add(map);
        map = new HashMap();
        map.put("id", 3);
        map.put("value", "配送日");
        searchConditionList.add(map);
        map = new HashMap();
        map.put("id", 4);
        map.put("value", "配送完了日");
        searchConditionList.add(map);

        result.put("searchConditionList", searchConditionList);

        result.put("shopList", shopService.selectShopListInit(userId, companyId));

        return SingleResult.success(result);
    }

    @Override
    public void downloadQooOrders(QooDownloadReq req, Long userId, Long companyId) {
        Map keyParams = handlerKeyParam(req);
        JSONObject keyObject = null;
        try {
            keyObject = restTemplate.getForObject(GlobalConstants.QOO_KEY_URL, JSONObject.class, keyParams);
        } catch (Exception e) {
            throw new BizExceptionI18(SysConstant.Order_Qoo_Sync_Fair);
        }

        String key = keyObject.getString("ResultObject");
        String ShippingStat = req.getShippingStat();
        String startDate = req.getStartDate().replaceAll("-", "");
        String endDate = req.getEndDate().replaceAll("-", "");

        Map params = getParams(key, ShippingStat, startDate, endDate);

        JSONObject forEntity = restTemplate.getForObject(GlobalConstants.QOO_DOWNLOAD_URL, JSONObject.class, params);
        List<OrderQoo10Do> orderQoo10Dos = JSON.parseArray(JSON.toJSONString(forEntity.get("ResultObject")), OrderQoo10Do.class);

        if (!CollectionUtils.isEmpty(orderQoo10Dos)) {
            orderQoo10Dos.forEach(orderQoo10Do -> {
                LambdaQueryWrapper<OrderQoo10Do> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(OrderQoo10Do::getOrderNo, orderQoo10Do.getOrderNo());
                int count = baseMapper.selectCount(wrapper);
                if (count > 0) {
                    return;
                }
                orderQoo10Do.setShopId(req.getShopId());
                orderQoo10Do.setCompanyId(companyId);
                baseMapper.insert(orderQoo10Do);
            });
        }
    }

    private Map handlerKeyParam(QooDownloadReq req) {
        ShopDo shopDo = shopDao.selectById(req.getShopId());
        Map map = new HashMap();
        map.put("id", shopDo.getQootenId());
        map.put("key", shopDo.getQootenKey());
        map.put("pwd", shopDo.getQootenPwd());

        return map;
    }

    @Override
    public SingleResult sendOut(QooSendOutReq req, Long userId, Long companyId) {
        //校验余额是否不足
        sufficientFundsCheck(companyId);
        List<String> failOrders = new ArrayList<>();
        List<OrderOutputAddReq> orderOutputAddReqList = new ArrayList<>();

        List<OrderQoo10Do> orderQoo10DoList = baseMapper.selectBatchIds(req.getIds());
        Map<Integer, List<OrderQoo10Do>> collectMap = orderQoo10DoList.stream().filter(orderQoo10Do -> orderQoo10Do.getPackNo() != null).collect(Collectors.groupingBy(OrderQoo10Do::getOrderNo));
        for (Map.Entry<Integer, List<OrderQoo10Do>> stringListEntry : collectMap.entrySet()) {

            Map<String, Object> result = sendOutOrder(stringListEntry, false, userId, companyId);

            if (result != null && result.get("orderOutputAddReq") != null) {
                orderOutputAddReqList.addAll((List) result.get("orderOutputAddReq"));
            }
            if (result != null && !CollectionUtils.isEmpty((List) result.get("failOrder"))) {
                failOrders.addAll((List) result.get("failOrder"));
            }
        }

//        if (req.getIsSolo() == 0) {
//            sendOutMatch(orderOutputAddReqList, userId, companyId);
//        }


        List<OrderQoo10Do> orderQoo10Dos = this.baseMapper.selectBatchIds(req.getIds());
        orderQoo10Dos.forEach(orderQoo10Do -> {
            operateRecordDao.operateAddRecord(SysConstant.OPERATE_CLICK_SEND, orderQoo10Do.getId(), userId, 6);
        });
        //
        // for (OrderOutputAddReq outputAddReq : orderOutputAddReqList) {
        //     StringBuilder sku = new StringBuilder();
        //     int count = 0;
        //     for (OrderOutputProductAddReq orderOutputProductAddReq : outputAddReq.getPackageList().get(0).getProductList()) {
        //         count = count + orderOutputProductAddReq.getCount();
        //         if (org.apache.commons.lang3.StringUtils.isNotBlank(sku)) {
        //             sku.append(",");
        //         }
        //         sku.append(productInfoDao.selectById(orderOutputProductAddReq.getProductId()).getCommoditySku());
        //     }
        //     outputAddReq.setSku(sku.toString());
        //     outputAddReq.setCount(count);
        // }
        Map map = new HashMap();
        map.put("orderList", orderOutputAddReqList);
        map.put("failedList", failOrders);
        map.put("storageList", storageDao.selectList(null));


        return SingleResult.success(map);
    }

    @Override
    public SingleResult sendOutMatch(List<OrderOutputAddReq> orderOutputAddReqList, Long userId, Long companyId) {
        List<String> failOrders = outputService.addQoo10List(orderOutputAddReqList, userId);
        if (failOrders.size() > 0) {
            return SingleResult.failure("300", SysConstant.EXPORT_OUT_ORDER_SUCCESS_ID, failOrders, orderOutputAddReqList.size() - failOrders.size());
        } else {
            return SingleResult.success(failOrders);
        }
    }

    private void sufficientFundsCheck(Long companyId) {
        if (!companyAccountService.getIsDue(companyId)) {
            throw new NotSufficientFundsException(ErrorEnum.NOT_SUFFICIENT_FUNDS);
        }
    }

    @Override
    public void markSendOut(List<Long> ids, Long userId, Long companyId) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new BizExceptionI18(SysConstant.Order_Qoo_Send_NotChoose);
        }
        LambdaUpdateWrapper<OrderQoo10Do> wrapper = new LambdaUpdateWrapper();
        wrapper.set(OrderQoo10Do::getIsSendOut, 1);
        wrapper.in(OrderQoo10Do::getId, ids);
        int count = this.baseMapper.update(null, wrapper);
        ids.forEach(id -> {
            operateRecordDao.operateAddRecord(SysConstant.OPERATE_MARK_SEND, id, userId, 6);
        });
    }

//    private void operateRecord(String str, OrderQoo10Do orderQoo10Do, Long userId) {
//        OperateRecordDo operateRecordDo = new OperateRecordDo();
//        operateRecordDo.setContent(str);
//        operateRecordDo.setOperateTime(new Date());
//        operateRecordDo.setOperateBy(userId);
//        operateRecordDo.setType(6);
//        operateRecordDo.setThirdId(orderQoo10Do.getId());
//        operateRecordDo.setDeleteFlag(0);
//        operateRecordDao.insert(operateRecordDo);
//    }

    private OrderOutputPackageDo handlerOutputPackageDo(OrderOutputDo orderOutputDo, Long userId) {
        OrderOutputPackageDo orderOutputPackageDo = new OrderOutputPackageDo();
        orderOutputPackageDo.setWidth(0);
        orderOutputPackageDo.setWeight(0);
        orderOutputPackageDo.setLength(0);
        orderOutputPackageDo.setHeight(0);
        orderOutputPackageDo.setCreateTime(new Date());
        orderOutputPackageDo.setCreateBy(userId);
        orderOutputPackageDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
        orderOutputPackageDo.setOrderOutputId(orderOutputDo.getId());
        orderOutputPackageDao.insert(orderOutputPackageDo);

        return orderOutputPackageDo;
    }

    private OrderOutputDo handlerOutputDo(List<OrderQoo10Do> qoo10DoList, Long userId, Long companyId) {
        OrderOutputDo orderOutputDo = new OrderOutputDo();
        OrderQoo10Do orderQoo10Do = qoo10DoList.get(0);
        orderOutputDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
        orderOutputDo.setCreateBy(userId);
        orderOutputDo.setCreateTime(new Date());
        orderOutputDo.setAddress(orderQoo10Do.getAddr1());
        orderOutputDo.setArea(orderQoo10Do.getAddr2());
        orderOutputDo.setTelPhone(orderQoo10Do.getBuyerTel());
        orderOutputDo.setTrackNumber(orderQoo10Do.getTrackingNo());
        orderOutputDo.setCompanyId(companyId);

        orderOutputDao.insert(orderOutputDo);
        orderOutputDo.setOrderOutputNumber(OrderCodeUtil.getOrderOutNumber(orderOutputDo.getId()));
        orderOutputDao.updateById(orderOutputDo);

        return orderOutputDo;
    }

    private Map getParams(String key, String ShippingStat, String startDate, String endDate) {
        Map map = new LinkedHashMap();
        map.put("key", key);
        map.put("v", "1.0");
        map.put("returnType", "json");
        map.put("method", "ShippingBasic.GetShippingInfo_v2");
        map.put("ShippingStat", ShippingStat);
        map.put("search_Sdate", startDate);
        map.put("search_Edate", endDate);

        return map;
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(OrderQoo10Do entityDo, Long userId) {
//        entityDo.setCreateBy(userId);
//        entityDo.setCreateTime(new Date());
//        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(OrderQoo10Do entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        OrderQoo10Do orderQoo10Do = this.baseMapper.selectById(id);
        return SingleResult.success(orderQoo10Do.getSystemMemo());
    }

    @Override
    public int update(QooUpdateReq req, Long userId) {
        OrderQoo10Do entityDo = baseMapper.selectById(req.getId());
        entityDo.setSystemMemo(req.getSystemMemo());
        baseMapper.updateById(entityDo);
        return baseMapper.updateById(entityDo);
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(OrderQoo10Do entityDo, Long userId) {
//        entityDo.setUpdateBy(userId);
//        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(OrderQoo10Do entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        OrderQoo10Do entityDo = baseMapper.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return baseMapper.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(OrderQoo10Do entityDo, Long userId) {
//        entityDo.setDeleteBy(userId);
//        entityDo.setDeleteTime(new Date());
    }

    @Override
    public QooDetailRes detail(Long id) {
        OrderQoo10Do entityDo = baseMapper.selectById(id);
        QooDetailRes res = new QooDetailRes();
        BeanUtils.copyProperties(entityDo, res);
        res.setShippingStatus(shipStatus().get(entityDo.getShippingStatus()));

        ShopDo shopDo = shopDao.selectById(entityDo.getShopId());
        if (shopDo != null) {
            res.setShopName(shopDo.getShopName());
        }
        CompanyDo companyDo = companyDao.selectById(entityDo.getCompanyId());
        if (companyDo != null) {
            res.setCompanyCode(companyDo.getCompanyCode());
        }
        res.setIsSendOut(entityDo.getIsSendOut() == 1 ? "是" : "否");
        res.setIsUploadExpress(entityDo.getIsUploadExpress() == 1 ? "是" : "否");


        //日志
        List<OperateRes> operateResList = operateRecordDao.getOperateList(id, 6);
        res.setOperateResList(operateResList);
        return res;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit(Long userId, Long companyId) {
        Map map = (Map) addInit(userId, companyId).getData();
        map.remove("shopList");
        map.remove("searchConditionList");
        return SingleResult.success(map);
    }

    /*@Override
    public List<QooListPageRes> getList(Map<String, String> map) {
        QueryWrapper<OrderQoo10Do> wrapper = queryBuild(map);
        List<OrderQoo10Do> list = this.list(wrapper);
        List<QooListPageRes> result = handlerListAfter(list);
        return result;
    }*/

    @Override
    public PageResult getListPage(OrderQooQueryBo bo) {
        IPage<OrderQoo10Do> page = new Page<>(bo.getCurrent(), bo.getPageSize());
        page = this.page(page, queryBuild(bo));
        List<QooListPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    @Override
    public void exportExcel(OrderQooQueryBo bo, HttpServletResponse response) throws IOException {
        List<OrderQoo10Do> orderQoo10DoList;
        if (!CollectionUtils.isEmpty(bo.getIds())) {
            orderQoo10DoList = baseMapper.selectBatchIds(bo.getIds());
        } else {
            orderQoo10DoList = baseMapper.selectList(queryBuild(bo));
        }

        List<QooExcelExportVo> excelExportVos = handlerQooDos(orderQoo10DoList);


        ExportParams exportParams = new ExportParams();
        exportParams.setCreateHeadRows(true);
        exportParams.setHeaderColor(IndexedColors.YELLOW.getIndex());
        ExcelUtils.exportExcel(excelExportVos, QooExcelExportVo.class, "Qoo10订单", exportParams, response);

    }

    private List<QooExcelExportVo> handlerQooDos(List<OrderQoo10Do> orderQoo10DoList) {
        List<QooExcelExportVo> excelExportVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(orderQoo10DoList)) {
            orderQoo10DoList.forEach(orderQoo10Do -> {
                QooExcelExportVo qooExcelExportVo = new QooExcelExportVo();
                BeanUtils.copyProperties(orderQoo10Do, qooExcelExportVo);
                qooExcelExportVo.setShippingStatus(shipStatus().get(orderQoo10Do.getShippingStatus()));
                qooExcelExportVo.setIsSendOut(orderQoo10Do.getIsSendOut() == 1 ? "是" : "否");
                qooExcelExportVo.setIsUploadExpress(orderQoo10Do.getIsUploadExpress() == 1 ? "是" : "否");
                excelExportVos.add(qooExcelExportVo);
            });
        }
        return excelExportVos;

    }

    //查询分页列表之后对列表数据的处理
    private List<QooListPageRes> handlerListAfter(List<OrderQoo10Do> list) {
        List<QooListPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(orderQoo10Do -> {
                QooListPageRes res = new QooListPageRes();
                BeanUtils.copyProperties(orderQoo10Do, res);
                if (orderQoo10Do.getShippingStatus().contains("(")) {
                    String substring = orderQoo10Do.getShippingStatus().substring(orderQoo10Do.getShippingStatus().indexOf("(") + 1, orderQoo10Do.getShippingStatus().indexOf(")"));
                    res.setShippingStatus(shipStatus().get(substring));
                } else if (StringUtils.isNotBlank(orderQoo10Do.getClaimStatus())) {
                    res.setShippingStatus(orderQoo10Do.getClaimStatus());
                }
                ShopDo shopDo = shopDao.selectById(orderQoo10Do.getShopId());
                if (shopDo != null) {
                    res.setShopName(shopDo.getShopName());
                }
                if (StringUtils.isBlank(orderQoo10Do.getOptionCode())) {
                    res.setOptionCode(orderQoo10Do.getSellerItemCode());
                }
                CompanyDo companyDo = companyDao.selectById(orderQoo10Do.getCompanyId());
                if (companyDo != null) {
                    res.setCompanyCode(companyDo.getCompanyCode());
                }
                res.setIsSendOut(orderQoo10Do.getIsSendOut() == 1 ? "是" : "否");
                res.setIsUploadExpress(orderQoo10Do.getIsUploadExpress() == 1 ? "是" : "否");
                result.add(res);
            });
        }
        return result;
    }

    private Map<String, String> shipStatus() {
        Map<String, String> map = new HashMap();
        map.put("1", "等待支付");
        map.put("2", "支付完成");
        map.put("3", "发货确认");
        map.put("4", "配送中");
        map.put("5", "配送完了");
        map.put("6", "取消/退换");
        return map;
    }

    private IPage<OrderQoo10Do> pageInit(Map<String, String> map) {
        IPage<OrderQoo10Do> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private LambdaQueryWrapper<OrderQoo10Do> queryBuild(OrderQooQueryBo bo) {
        LambdaQueryWrapper<OrderQoo10Do> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(bo.getOrderNo()), OrderQoo10Do::getOrderNo, bo.getOrderNo());
        lqw.like(StringUtils.isNotBlank(bo.getPackNo()), OrderQoo10Do::getPackNo, bo.getPackNo());
        lqw.like(StringUtils.isNotBlank(bo.getBuyerMobile()), OrderQoo10Do::getBuyerMobile, bo.getBuyerMobile());
        lqw.like(StringUtils.isNotBlank(bo.getBuyer()), OrderQoo10Do::getBuyer, bo.getBuyer());
        if (StringUtils.isNotBlank(bo.getOptionCode()))
            lqw.and(new Consumer<LambdaQueryWrapper<OrderQoo10Do>>() {
                @Override
                public void accept(LambdaQueryWrapper<OrderQoo10Do> orderQoo10DoLambdaQueryWrapper) {
                    orderQoo10DoLambdaQueryWrapper.like(StringUtils.isNotBlank(bo.getOptionCode()), OrderQoo10Do::getOptionCode, bo.getOptionCode());
                    orderQoo10DoLambdaQueryWrapper.or();
                    orderQoo10DoLambdaQueryWrapper.like(StringUtils.isNotBlank(bo.getOptionCode()), OrderQoo10Do::getSellerItemCode, bo.getOptionCode());
                }
            });
        if (StringUtils.isNotBlank(bo.getShippingStatus())) {
            if ("6".equals(bo.getShippingStatus())) {
                lqw.like(OrderQoo10Do::getShippingStatus, ":");
            } else {
                lqw.like(OrderQoo10Do::getShippingStatus, bo.getShippingStatus());
            }
        }
        lqw.eq(Objects.nonNull(bo.getIsSendOut()), OrderQoo10Do::getIsSendOut, bo.getIsSendOut());
        lqw.eq(Objects.nonNull(bo.getCompanyId()), OrderQoo10Do::getCompanyId, bo.getCompanyId());
        lqw.ge(Objects.nonNull(bo.getStartDate()), OrderQoo10Do::getOrderDate, bo.getStartDate());
        lqw.le(Objects.nonNull(bo.getEndDate()), OrderQoo10Do::getOrderDate, bo.getEndDate());
        lqw.orderByDesc(OrderQoo10Do::getId);
        return lqw;
    }


    private Map<String, Object> sendOutOrder(Map.Entry<Integer, List<OrderQoo10Do>> entry, boolean b, Long userId, Long companyId) {
        Map<String, Object> result = new HashMap<>();

        List<String> failOrder = new ArrayList<>();
        List<OrderOutputAddReq> orderOutputAddReqList = new ArrayList<>();
        OrderOutputAddReq orderOutputAddReq = new OrderOutputAddReq();
        orderOutputAddReq.setPlatform("qoo10");
        orderOutputAddReq.setPlatformNumber(entry.getValue().get(0).getOrderNo().toString());
        orderOutputAddReq.setOrderType(1);
        orderOutputAddReq.setSendDate(new Date());
        orderOutputAddReq.setShopId(entry.getValue().get(0).getShopId());
        orderOutputAddReq.setCompanyId(entry.getValue().get(0).getCompanyId());
        orderOutputAddReq.setOrderNo(entry.getValue().get(0).getOrderNo().toString());
        if (StringUtils.isNotBlank(entry.getValue().get(0).getOptionCode())) {
            orderOutputAddReq.setSku(entry.getValue().get(0).getOptionCode());
        } else {
            orderOutputAddReq.setSku(entry.getValue().get(0).getSellerItemCode());
        }
        if (entry.getValue().get(0).getDeliveredDate() != null) {
            orderOutputAddReq.setDeliveryDate(entry.getValue().get(0).getDeliveredDate().toString());
        }
        orderOutputAddReq.setReceiverName(entry.getValue().get(0).getReceiver());
        if (StringUtils.isNotBlank(entry.getValue().get(0).getReceiverTel()) && !"+81--".equals(entry.getValue().get(0).getReceiverTel())) {
            orderOutputAddReq.setTelPhone(entry.getValue().get(0).getReceiverTel().replaceAll("\\+81-", ""));
        } else if (StringUtils.isNotBlank(entry.getValue().get(0).getReceiverMobile()) && !"+81--".equals(entry.getValue().get(0).getReceiverMobile())) {
            orderOutputAddReq.setTelPhone(entry.getValue().get(0).getReceiverMobile().replaceAll("\\+81-", ""));
        }

        if (entry.getValue().get(0).getZipCode() != null) {
            orderOutputAddReq.setPostCode(entry.getValue().get(0).getZipCode().toString());
        }
//        orderOutputAddReq.setArea();
        orderOutputAddReq.setAddress(entry.getValue().get(0).getAddr1() + entry.getValue().get(0).getAddr2());

        List<OrderOutputProductAddReq> productAddList = new ArrayList<>();

        Map<String, Integer> skuMap = new HashMap(); //key--sku,value--count
        StringBuilder orderNoBuilder = new StringBuilder();
        //默认仓库捆包发货
        for (OrderQoo10Do orderQoo10Do : entry.getValue()) {
            String sku = "";
            if (StringUtils.isNotBlank(orderQoo10Do.getOptionCode())) {
                sku = orderQoo10Do.getOptionCode();
            } else {
                sku = orderQoo10Do.getSellerItemCode();
            }
            String[] split = sku.split(",");
            if (split.length > 0) {
                for (String s : split) {
                    skuMap.merge(s, orderQoo10Do.getOrderQty(), Integer::sum);
                }
            }
        }
        orderOutputAddReq.setOrderNoTips(orderNoBuilder.toString());

        //先判断有没有该商品
        List<ProductCombinationDo> productCombinationDoList = null;
        for (Map.Entry<String, Integer> stringIntegerEntry : skuMap.entrySet()) {
            ProductInfoDo productInfoDo = productInfoService.getProductDo(stringIntegerEntry.getKey(), companyId);
            if (productInfoDo == null) {
                failOrder.add("没有该商品：" + stringIntegerEntry.getKey());
                result.put("failOrder", failOrder);
                return result;
            }
            if (productInfoDo.getTypeOfProduct().equals(StaticDict.Product_Info_Type.Combination.getValue())) {
                LambdaQueryWrapper<ProductCombinationDo> productCombinationWrapper = new LambdaQueryWrapper<>();
                productCombinationWrapper.eq(ProductCombinationDo::getParentId, productInfoDo.getId());
                productCombinationDoList = productCombinationService.getBaseMapper().selectList(productCombinationWrapper);
                boolean flag = true;
                for (int i = 0; i < productCombinationDoList.size(); i++) {
                    ProductCombinationDo productCombinationDo = productCombinationDoList.get(i);
                    //判断生效期
                    if (!(productCombinationDo.getEffective() == 0 || (productCombinationDo.getEffectBeginTime().before(new Date()) && productCombinationDo.getEffectEndTime().after(new Date())))) {
                        productCombinationDoList.remove(i);
                        i--;
                        continue;
                    }
                    ProductInfoDo child = productInfoService.getById(productCombinationDo.getChildId());
                    if (child == null) {
                        productCombinationDoList.remove(i);
                        i--;
                        continue;
                    }
                    flag = false;
                }

                if (flag) {
                    //组合产品下无产品
                    failOrder.add("组合产品：" + productInfoDo.getCommoditySku() + " 子产品 不存在");
                    result.put("failOrder", failOrder);
                    return result;
                }
            }
        }
        //优先仓库
        Long stateId = mRegionService.getStateIdByPostCode(entry.getValue().get(0).getZipCode());
        //仓库
        LambdaQueryWrapper<StorageDo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StorageDo::getSupportShip, 1);
        List<StorageDo> storageDos = storageDao.selectList(lambdaQueryWrapper);
        Collections.sort(storageDos, new Comparator<StorageDo>() {
            @Override
            public int compare(StorageDo o1, StorageDo o2) {
                if (o1.getId().equals(o2.getId())) {
                    return 0;
                }
                if (stateId <= 8) {
                    //大阪地区优先发货仓库
                    if (o1.getId() == 9L) {
                        return -1;
                    } else if (o2.getId() == 9L) {
                        return 1;
                    } else {
                        return o1.getId() < o2.getId() ? -1 : 1;
                    }
                } else {
                    //东京仓库优先发货仓库
                    if (o1.getId() == 10L) {
                        return -1;
                    } else if (o2.getId() == 10L) {
                        return 1;
                    } else {
                        return o1.getId() < o2.getId() ? -1 : 1;
                    }
                }
            }
        });
        //判断库存
        Long storageId = null;
        storage:
        for (StorageDo storageDo : storageDos) {
            for (Map.Entry<String, Integer> stringIntegerEntry : skuMap.entrySet()) {
                ProductInfoDo productInfoDo = productInfoService.getProductDo(stringIntegerEntry.getKey(), companyId);
                if (!productInfoDo.getTypeOfProduct().equals(StaticDict.Product_Info_Type.Combination.getValue())) {
                    // LambdaQueryWrapper<StockRecordDo> stockRecordDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    // stockRecordDoLambdaQueryWrapper.eq(StockRecordDo::getShopId, entry.getValue().get(0).getShopId())
                    //         .eq(StockRecordDo::getProductInfoId, productInfoDo.getId())
                    //         .eq(StockRecordDo::getStorageId, storageDo.getId());
                    //
                    // StockRecordDo stockRecordDo = stockRecordDao.selectOne(stockRecordDoLambdaQueryWrapper);
                    // int count = stockRecordDao.getOrderOutCount(productInfoDo.getId(), entry.getValue().get(0).getShopId(), storageDo.getId());
                    int canUseCount = stockRecordService.getStockCount(companyId, entry.getValue().get(0).getShopId(), storageDo.getId(), productInfoDo.getId(), stringIntegerEntry.getValue());

                    if (!(canUseCount >= stringIntegerEntry.getValue())) {
                        //库存不够
                        continue storage;
                    }

                } else if (productCombinationDoList != null) {
                    for (ProductCombinationDo productCombinationDo : productCombinationDoList) {
                        // LambdaQueryWrapper<StockRecordDo> stockRecordDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        // stockRecordDoLambdaQueryWrapper.eq(StockRecordDo::getShopId, entry.getValue().get(0).getShopId())
                        //         .eq(StockRecordDo::getProductInfoId, productCombinationDo.getChildId())
                        //         .eq(StockRecordDo::getStorageId, storageDo.getId());
                        //
                        // StockRecordDo stockRecordDo = stockRecordDao.selectOne(stockRecordDoLambdaQueryWrapper);
                        int canUseCount = stockRecordService.getStockCount(companyId, entry.getValue().get(0).getShopId(), storageDo.getId(), productCombinationDo.getChildId(), productCombinationDo.getCount());
                        if (!(canUseCount >= productCombinationDo.getCount())) {
                            continue storage;
                        }
                    }
                } else {
                    continue storage;
                }
            }
            storageId = storageDo.getId();
            break;
        }
        if (storageId == null) {
            failOrder.add(entry.getValue().get(0).getOrderNo() + "库存不足");
            result.put("failOrder", failOrder);
            return result;
        }
        for (Map.Entry<String, Integer> stringIntegerEntry : skuMap.entrySet()) {
            ProductInfoDo productInfoDo = productInfoService.getProductDo(stringIntegerEntry.getKey(), companyId);
            if (!productInfoDo.getTypeOfProduct().equals(StaticDict.Product_Info_Type.Combination.getValue())) {
                OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
                productDo1.setProductId(productInfoDo.getId());
                productDo1.setCommoditySku(productInfoDo.getCommoditySku());
                productDo1.setCount(stringIntegerEntry.getValue());
                productAddList.add(productDo1);
            } else if (productCombinationDoList != null) {
                for (ProductCombinationDo productCombinationDo : productCombinationDoList) {
                    OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
                    productDo1.setProductId(productCombinationDo.getChildId());
//                        productDo1.setCommoditySku(child.getCommoditySku());
                    productDo1.setCount(productCombinationDo.getCount());
                    productAddList.add(productDo1);
                }
            }
        }

        //捆包信息
        OrderOutputPackageAddReq packageDetail = new OrderOutputPackageAddReq();
        List<OrderOutputPackageAddReq> packageAddReqList = new ArrayList<>();
        packageDetail.setProductList(productAddList);
        packageAddReqList.add(packageDetail);
        orderOutputAddReq.setStorageId(storageId);
        orderOutputAddReq.setPackageList(packageAddReqList);
        orderOutputAddReqList.add(orderOutputAddReq);
//        List<Map.Entry<String, Integer>> failedSkuList2 = new ArrayList<>();
//        //判断失败SKU信息，默认仓库无库存
//        if (failedSkuList.size() > 0) {
//            //查找第二个捆包仓库
//            LambdaQueryWrapper<StorageDo> lambdaQueryWrapper = new LambdaQueryWrapper();
//            lambdaQueryWrapper.eq(StorageDo::getSupportShip, 1).ne(StorageDo::getId, storageId);
//            List<StorageDo> storageDos = storageDao.selectList(lambdaQueryWrapper);
//            storageId = storageDos.get(0).getId();
//
//
//            for (Map.Entry<String, Integer> stringIntegerEntry : failedSkuList) {
//                ProductInfoDo productInfoDo = productInfoService.getProductDo(stringIntegerEntry.getKey(), companyId);
//                if (productInfoDo == null) {
//                    failOrder.add("没有该商品：" + stringIntegerEntry.getKey());
//                    result.put("failOrder", failOrder);
//                    return result;
//                }
//
//                LambdaQueryWrapper<StockRecordDo> stockRecordDoLambdaQueryWrapper = new LambdaQueryWrapper();
//                stockRecordDoLambdaQueryWrapper.eq(StockRecordDo::getShopId, entry.getValue().get(0).getShopId())
//                        .eq(StockRecordDo::getProductInfoId, productInfoDo.getId())
//                        .eq(StockRecordDo::getStorageId, storageId);
//
//                StockRecordDo stockRecordDo = stockRecordDao.selectOne(stockRecordDoLambdaQueryWrapper);
//                int count = stockRecordDao.getOrderOutCount(productInfoDo.getId(), entry.getValue().get(0).getShopId(), storageId);
//                double[] size = new double[4];
//                Double shipPirce = 99999d;
//                if (!(stockRecordDo != null && stockRecordDo.getCanSellCount() - count >= stringIntegerEntry.getValue())) {
//                    failedSkuList2.add(stringIntegerEntry);
//                    continue;
//                }
//
//                OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
//                productDetail.setProductId(productInfoDo.getId());
//                productDetail.setCount(stringIntegerEntry.getValue());
//                productAddList.add(productDetail);
//            }
//            //捆包信息
//            packageDetail = new OrderOutputPackageAddReq();
//
//            packageAddReqList = new ArrayList<>();
//            packageDetail.setProductList(productAddList);
//            packageAddReqList.add(packageDetail);
//            OrderOutputAddReq addReq = new OrderOutputAddReq();
//            BeanUtils.copyProperties(orderOutputAddReq, addReq);
//            addReq.setStorageId(storageId);
//            addReq.setPackageList(packageAddReqList);
//            if (failedSkuList2.size() != failedSkuList.size()) {
//                orderOutputAddReqList.add(addReq);
//            }
//        }
//        if (failedSkuList2.size() > 0) {
//            StringBuilder stringBuilder = new StringBuilder();
//            for (Map.Entry<String, Integer> stringIntegerEntry : failedSkuList2) {
//                storageId = 0L;
//                ProductInfoDo productInfoDo = productInfoService.getProductDo(stringIntegerEntry.getKey(), companyId);
//                if (productInfoDo == null) {
//                    failOrder.add("没有该商品：" + stringIntegerEntry.getKey());
//                    result.put("failOrder", failOrder);
//                    return result;
//                }
//                LambdaQueryWrapper<StorageDo> queryWrapper = new LambdaQueryWrapper();
//                queryWrapper.eq(StorageDo::getCountryType, 1);
//                List<StorageDo> storageDoList = storageDao.selectList(queryWrapper);
//                storageId = 0L;
//                long productId = productInfoDo.getId();
//                double shipPirce = 99999D;
//                for (StorageDo storageDo : storageDoList) {//遍历仓库是否都有库存
//                    LambdaQueryWrapper<StockRecordDo> wrapper2 = new LambdaQueryWrapper();
//                    double[] size = shipPriceService.countSameSkuSize(new double[4], productId,
//                            1);
//                    wrapper2.eq(StockRecordDo::getShopId, entry.getValue().get(0).getShopId())
//                            .eq(StockRecordDo::getProductInfoId, productId)
//                            .eq(StockRecordDo::getStorageId, storageDo.getId());
//                    StockRecordDo stockRecordDo1 = stockRecordDao.selectOne(wrapper2);
//                    int noDeliveredCount1 = stockRecordDao.getOrderOutCount(productId, entry.getValue().get(0).getShopId(), storageDo.getId())
//                            + stockRecordDao.getOrderOutTurn2FbaCount(productId, entry.getValue().get(0).getShopId(), storageDo.getId());
//                    if (stockRecordDo1 != null && stockRecordDo1.getCanSellCount() - noDeliveredCount1 >= stringIntegerEntry.getValue()) {
//                        List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(entry.getValue().get(0).getZipCode(),
//                                size, entry.getValue().get(0).getCodPrice().intValue(),
//                                0, storageDo.getId(), 1, entry.getValue().get(0).getCompanyId());
//                        if (shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0) continue;
//                        if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
//                            shipPirce = shipPriceDos.get(0).getPrice();
//                            storageId = storageDo.getId();
//                        }
//                    }
//                }
//                if (storageId != 0) {
//                    OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
//                    productDetail.setProductId(productInfoDo.getId());
//                    productDetail.setCount(stringIntegerEntry.getValue());
//                    productAddList = new ArrayList<>();
//                    productAddList.add(productDetail);
//
//                    packageDetail = new OrderOutputPackageAddReq();
//                    packageAddReqList = new ArrayList<>();
//                    packageDetail.setProductList(productAddList);
//                    OrderOutputAddReq addReq = new OrderOutputAddReq();
//                    BeanUtils.copyProperties(orderOutputAddReq, addReq);
//                    packageAddReqList.add(packageDetail);
//                    addReq.setStorageId(storageId);
//                    addReq.setPackageList(packageAddReqList);
//                    orderOutputAddReqList.add(addReq);
//                } else {
//                    stringBuilder.append("(" + stringIntegerEntry.getKey() + ")");
//                }
//            }
//            if (stringBuilder.length() > 0) {
//                failOrder.add("(" + stringBuilder.toString() + "库存不足)");
//            }
//        }
        if (failOrder.size() > 0) {
            orderOutputAddReqList.clear();
        }
        result.put("orderOutputAddReq", orderOutputAddReqList);
        result.put("failOrder", failOrder);

        return result;
    }

}
